<?php
class Controller_App_Search extends Controller_App_Template
{
    public function __construct ($req, $res)
    {
        $this->template = "smarty:app/search_result";
        parent::__construct($req, $res);
    }

    // 商品详情
    public function action_index ()
    {
        $query = $this->request->query();
        $key   = Arr::get($query, 'key');
        $sort  = Arr::get($query, 'sort');
        $page  = Arr::get($query, 'page', 1);
        $tag   = Arr::get($query, 'tag', 0);
        $limit = 10;
        $page  = max(1, $page);
        $offset = ($page - 1) * $limit;

        $this->template->set('global_search', array(
            'key' => $key,
            'page' => $page,
            'sort' => $sort,
            'tag'  => $tag,
        ));

        if (empty($key))
        {
            $this->template->set('goodsResult', array('total' => 0, 'list' => array()));
            $this->template->set('shopsResult', array('total' => 0, 'list' => array()));
            $this->template->set('title', '搜索');
        }
        else
        {
            $this->template->set('goodsResult', App_Goods::search($key, $sort, $offset, $limit));
            $this->template->set('shopsResult', App_Shop::search($key, $sort, $offset, $limit));
            $this->template->set('title', '搜索: ' . $key);
        }
        
        $title_json  = App_Util::buildClientTitleJson('back', 'block', '搜索', 'message', 'none', '');
        $bottom_json = App_Util::buildClientBottomJson('none', 'homepage');
        
        $this->template->set('title_json',   $title_json);
        $this->template->set('bottom_json',  $bottom_json);
    }

    // 商品 AJAX
    public function action_goods ()
    {
        $query = $this->request->query();
        $key   = Arr::get($query, 'key');
        $sort  = Arr::get($query, 'sort');
        $page  = Arr::get($query, 'page', 1);
        $tag   = Arr::get($query, 'tag', 0);
        $limit = 10;
        $page  = max(1, $page);
        $offset = ($page - 1) * $limit;

        $goodsList = App_Goods::search($key, $sort, $offset, $limit, $tag);
        $ret = array(
            'status' => 0,
            'html'   => View::factory('smarty:app/homepage_goods')
                            ->set('goodsResult', $goodsList)
                            ->render(),
                );

        echo json_encode($ret); exit;
    }
}
